<?php
/**
 * Created by PhpStorm.
 * User: yiyu
 * Email: smalleasyu@gmail.com
 * Date: 2020-01-19 22:24:50
 * Desc:
 */

namespace app\base\service\WeChat;

use app\base\service\BaseService;
use app\base\model\user\UserWx;
use function Clue\StreamFilter\fun;
use EasyWeChat\Factory;
use app\core\exception\BusinessException;
use app\core\exception\ErrorCode;
use app\core\log\Log4dd;

class MiniProgramSubscribeMessageService extends BaseService
{

    public $app;
    public $app_id;

    const MINI_WISH_DETAIL_PAGE = '/pages/wish/detail';

    public function __construct($app_id = '')
    {
        $config = WeChatBaseService::instance()->getConfigByAppId($app_id, 'mini_program');
        $this->app_id = $config['app_id'];
        $this->app = Factory::miniProgram($config);
    }

    /**
     * Desc: 发送心愿进度消息(订单进度提醒	订单类型、订单编号、订单状态、更新时间、温馨提示)
     * Date: 2020/2/29 22:33
     * Author: yiyu
     * @param $data
     * @param $user_id
     * @param string $to_open_id
     * @param string $page
     * @return bool
     */
    public function sendWishProgressNoticeMsg($data, $user_id, $to_open_id = '', $page = '')
    {

        if(empty($to_open_id)){
            //获取open_id
            $to_open_id = UserWx::getOpenIdByUserId($user_id, $this->app_id, UserWx::MINI_PROGRAM_OPEN_ID_TYPE);
        }

        Log4dd::info('订阅号消息，发送心愿进度消息', ['open_id' => $to_open_id, 'args' => func_get_args()]);

        if (!isset($data['group_id']) || empty($data['group_id'])) {
            return false;
        }

        if (empty($to_open_id)) {
            return false;
        }

        if (empty($page)) {
            $page = self::MINI_WISH_DETAIL_PAGE . '?group_id=' . $data['group_id'];
        }

        if(!isset($data['first']) || empty($data['first'])){
            $data['first'] = '我发起的好物心愿';
        }

        if (mb_strlen($data['first']) > 20) {
            $data['first'] = '我发起的好物心愿';
        }

        $message = [
            'template_id' => 'BpEPpz8rVf2mVEzd6pQNsFXR2X5x5uuFq1W0fLMkYcM', // 所需下发的订阅模板id
            'touser' => $to_open_id,     // 接收者（用户）的 openid
            'page' => $page,       // 点击模板卡片后的跳转页面，仅限本小程序内的页面。支持带参数,（示例index?foo=bar）。该字段不填则模板无跳转。
            'data' => [         // 模板内容，格式形如 { "key1": { "value": any }, "key2": { "value": any } }
                'thing2' => [
                    'value' => $data['first'] ?? '我发起的好物心愿',//20个以内字符	可汉字、数字、字母或符号组合
                ],
                'character_string1' => [
                    'value' => $data['keyword1'] ?? config('wish_num_prefix') . $data['group_id'],//32位以内数字、字母或符号	可数字、字母或符号组合
                ],
                'phrase3' => [
                    'value' => $data['keyword2'] ?? '得到支持',//5个以内纯汉字，例如：配送中
                ],
                'time4' => [
                    'value' => $data['keyword3'] ?? date('Y年m月d日 H:i:s'),//24小时制时间格式（支持+年月日）	例如：15:01，或：2019年10月1日 15:01
                ],
                'thing5' => [
                    'value' => $data['keyword4'] ?? '点击此处打开心愿详情',//20个字符以内 可汉字、数字、字母或符号组合
                ],
            ],
        ];

        $result = $this->app->subscribe_message->send($message);

        Log4dd::info('订阅号消息，发送心愿进度消息结果', ['open_id' => $to_open_id, 'result' => $result]);

    }

    /**
     * Desc: 发送心愿达标消息（交易成功提醒	商品名称、交易单号、交易时间、温馨提示）
     * Date: 2020/2/29 22:33
     * Author: yiyu
     * @param $data
     * @param $user_id
     * @param string $to_open_id
     * @param string $page
     * @return bool
     */
    public function sendWishFinishNoticeMsg($data, $user_id, $to_open_id = '', $page = '')
    {

        if(empty($to_open_id)){
            //获取open_id
            $to_open_id = UserWx::getOpenIdByUserId($user_id, $this->app_id, UserWx::MINI_PROGRAM_OPEN_ID_TYPE);
        }

        Log4dd::info('订阅号消息，发送心愿达标消息', ['open_id' => $to_open_id, 'args' => func_get_args()]);

        if (!isset($data['group_id']) || empty($data['group_id'])) {
            return false;
        }

        if (empty($to_open_id)) {
            return false;
        }

        if (empty($page)) {
            $page = self::MINI_WISH_DETAIL_PAGE . '?group_id=' . $data['group_id'];
        }

        if(!isset($data['first']) || empty($data['first'])){
            $data['first'] = '我发起的好物心愿';
        }

        if (mb_strlen($data['first']) > 20) {
            $data['first'] = '我发起的好物心愿';
        }

        $message = [
            'template_id' => 'nRV0Tbg8hLCVOQiaC-fpFgz-VZMApep8HUxXa96F5NE', // 所需下发的订阅模板id
            'touser' => $to_open_id,     // 接收者（用户）的 openid
            'page' => $page,       // 点击模板卡片后的跳转页面，仅限本小程序内的页面。支持带参数,（示例index?foo=bar）。该字段不填则模板无跳转。
            'data' => [         // 模板内容，格式形如 { "key1": { "value": any }, "key2": { "value": any } }
                'thing2' => [
                    'value' => $data['first'] ?? '我发起的好物心愿',
                ],
                'character_string1' => [
                    'value' => $data['keyword1'] ?? config('wish_num_prefix') . $data['group_id'],
                ],
                'date3' => [
                    'value' => $data['keyword2'] ?? date('Y年m月d日 H:i:s'),
                ],
                'thing5' => [
                    'value' => $data['keyword3'] ?? '你发起的好物心愿已达成！点击可查看详情',
                ],
            ],
        ];

        $result = $this->app->subscribe_message->send($message);

        Log4dd::info('订阅号消息，发送心愿达标消息结果', ['open_id' => $to_open_id, 'result' => $result]);

    }

    /**
     * Desc: 发送物流消息（订单发货提醒	订单编号、商品详情、快递公司、快递单号、温馨提示）
     * Date: 2020/2/29 22:34
     * Author: yiyu
     * @param $data
     * @param $user_id
     * @param string $to_open_id
     * @param string $page
     * @return bool
     */
    public function sendLogisticsNoticeMsg($data, $user_id, $to_open_id = '', $page = '')
    {

        if(empty($to_open_id)){
            //获取open_id
            $to_open_id = UserWx::getOpenIdByUserId($user_id, $this->app_id, UserWx::MINI_PROGRAM_OPEN_ID_TYPE);
        }

        Log4dd::info('订阅号消息，发送物流消息', ['open_id' => $to_open_id, 'args' => func_get_args()]);

        if (!isset($data['group_id']) || empty($data['group_id'])) {
            return false;
        }

        if (empty($to_open_id)) {
            return false;
        }

        if (empty($page)) {
            $page = self::MINI_WISH_DETAIL_PAGE . '?group_id=' . $data['group_id'];
        }

        if(!isset($data['keyword1']) || empty($data['keyword1'])){
            $data['keyword1'] = '我发起的好物心愿';
        }

        if (mb_strlen($data['keyword1']) > 20) {
            $data['keyword1'] = '我发起的好物心愿';
        }

        $message = [
            'template_id' => '_k_imYUYQsgyJZBxGoN-VwTmwlN09jJhLCaSpQgbB34', // 所需下发的订阅模板id
            'touser' => $to_open_id,     // 接收者（用户）的 openid
            'page' => $page,       // 点击模板卡片后的跳转页面，仅限本小程序内的页面。支持带参数,（示例index?foo=bar）。该字段不填则模板无跳转。
            'data' => [         // 模板内容，格式形如 { "key1": { "value": any }, "key2": { "value": any } }
                'character_string1' => [
                    'value' => $data['first'] ?? config('wish_num_prefix') . $data['group_id']
                ],
                'thing2' => [
                    'value' => $data['keyword1'] ?? '我发起的好物心愿',
                ],
                'name3' => [
                    'value' => $data['keyword2'] ?? '点击查看物流详情',
                ],
                'character_string4' => [
                    'value' => $data['keyword3'] ?? '点击查看物流详情',
                ],
                'thing7' => [
                    'value' => $data['keyword4'] ?? '你发起的好物心愿已发货！点击可查看详情',
                ],
            ],
        ];

        $result = $this->app->subscribe_message->send($message);

        Log4dd::info('订阅号消息，发送物流消息结果', ['open_id' => $to_open_id, 'result' => $result]);

    }


    public function sendErrorNoticeMsg($data)
    {

        $error = $data['error'] ?? '发生错误了，赶紧查看';
        $notice = $data['notice'] ?? '发生错误了，赶紧查看';
        $message = [
            'template_id' => '_k_imYUYQsgyJZBxGoN-VwTmwlN09jJhLCaSpQgbB34', // 所需下发的订阅模板id
            'touser' => 'oA20w5SPjhTEki8N5QStjhIkxojU',     // 接收者（用户）的 openid
            'page' => '',       // 点击模板卡片后的跳转页面，仅限本小程序内的页面。支持带参数,（示例index?foo=bar）。该字段不填则模板无跳转。
            'data' => [         // 模板内容，格式形如 { "key1": { "value": any }, "key2": { "value": any } }
                'date3' => [
                    'value' => $data['date'] ?? date('Y年m月d日 H:i:s'),
                ],
                'thing5' => [
                    'value' => $data['line'] ?? 0,
                ],
                'thing6' => [
                    'value' => mb_strlen($error) > 20 ? mb_substr($error, 0, 20) : $error,
                ],
                'thing7' => [
                    'value' => mb_strlen($notice) > 20 ? mb_substr($notice, 0, 20) : $notice,
                ],
            ],
        ];

        $result = $this->app->subscribe_message->send($message);

        Log4dd::info('订阅号消息，发送错误提示消息结果', ['result' => $result]);
    }

}